/*
Continuous Testing Toolkit
Copyright (C) 2009 Paul R. Holser, Jr.

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package org.infinitest.toolkit.runners;

import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.internal.runners.model.MultipleFailureException;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.junit.runners.model.TestClass;

class RunEnclosedThenEnclosingAfters extends RunEnclosingAndEnclosedFrameworkMethod {
    RunEnclosedThenEnclosingAfters(Statement next, Object enclosedInstance, TestClass enclosed,
        Object enclosingInstance, TestClass enclosing) {

        super(next);
        add(enclosedInstance, enclosed);
        add(enclosingInstance, enclosing);
    }

    @Override
    public void evaluate() throws Throwable {
        List<Throwable> errors = new ArrayList<Throwable>();

        try {
            next.evaluate();
        } catch (Throwable e) {
            errors.add(e);
        } finally {
            for (Map.Entry<Object, List<FrameworkMethod>> each : targetsToMethods.entrySet()) {
                for (FrameworkMethod after : each.getValue()) {
                    try {
                        after.invokeExplosively(each.getKey());
                    }
                    catch (Throwable e) {
                        errors.add(e);
                    }
                }
            }
        }

        if (errors.isEmpty())
            return;
        if (errors.size() == 1)
            throw errors.get(0);
        throw new MultipleFailureException(errors);
    }

    @Override
    protected Class<? extends Annotation> frameworkMethodAnnotationClass() {
        return After.class;
    }
}
